/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.product.web.ProductCategoryAction
   Module Description   :

   Date Created      : 2010/5/13
   Original Author   : feeling
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.product.web;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import tw.idv.cut7man.pageable.TagProperties;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.JspUtil;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.core.menu.service.MenuService;
import com.yaodian100.ec.category.entity.Category;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.product.entity.ProdCatSE;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.ProductCategory;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.shelf.entity.ViewShelfProduct;
import com.yaodian100.ec.shelf.service.ShelfService;

/**
 * @author feeling
 * 
 */
public class ProductCategoryAction extends ActionSupport implements Preparable {

	/**
	 * serial version
	 */
	private static final long serialVersionUID = -3704242370042766314L;
	private final Logger logger = LoggerFactory.getLogger(ProductCategoryAction.class);
	@Resource
	private ProductService productService;
	@Resource
	private ShelfService shelfService;
	@Resource
	private CategoryService categoryService;
	@Resource
	private MenuService menuService;
	private String categoryIdParam;
	private String[] productCategoryIds;
	private String[] delProductCategoryIds;
	private String[] copyProductCategoryIds;
	private String[] editProductCategoryIds;
	private String[] showSeqs;
	private List<Object> productCategories;
	private List<ViewShelfProduct> viewShelfProducts;
	private String categoryId;
	private boolean checkPrice;
	private String categoryResult;
	private String categoryPath;
	private int productCategoriesSize;
	private final String[] defaultSort = new String[] { "showSeq asc", "productId desc" };
	private List productAttributeParam;
	private Menu attributeMenu;
	final String errorMsg = ":该分类未上架或不存在、已被下架、删除或无该权限查看";
	private String keyword;
	@Resource
	private BaseManager baseMgr;

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String copyMove() throws Exception {
		if (null != copyProductCategoryIds && StringUtils.isNotBlank(categoryId)) {
			categoryId = StringUtils.replace(categoryId, " ", "");
			Category category = categoryService.getAvailableCategory(Long.parseLong(categoryId));
			if (null != category) {
				boolean result = productService.updateProductCategory(copyProductCategoryIds, categoryId, "copy");
				if (result) {
					addActionMessage("复制成功");
				} else {
					addActionError("复制失败");
				}
			} else {
				addActionMessage(categoryId + errorMsg);
			}
		}
		return searchMove();
	}

	public String del() throws Exception {
		if (null != delProductCategoryIds) {
			try {
				productService.delProdCat(delProductCategoryIds);
				addActionMessage("删除成功");
			} catch (Exception e) {

				addActionError("删除失败");
			}
		}
		return search();
	}

	public String delMove() throws Exception {
		if (null != delProductCategoryIds) {
			boolean result = productService.deleteProductCategory(delProductCategoryIds);
			if (result) {
				addActionMessage("删除成功");
			} else {
				addActionError("删除失败");
			}
		}
		return searchMove();
	}

	public String edit() throws Exception {
		try {
			productService.publishProdCat(categoryIdParam);

			addActionMessage("修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("修改失败");
		}

		return search();
	}

	public String editMove() throws Exception {
		if (null != editProductCategoryIds && StringUtils.isNotBlank(categoryId)) {
			categoryId = StringUtils.replace(categoryId, " ", "");
			Category category = categoryService.getAvailableCategory(Long.parseLong(categoryId));
			if (null != category) {
				boolean result = productService.updateProductCategory(editProductCategoryIds, categoryId, "upd");
				if (result) {
					addActionMessage("修改成功");
				} else {
					addActionError("修改失败");
				}
			} else {
				addActionMessage(categoryId + errorMsg);
			}
		}
		return searchMove();
	}

	public Menu getAttributeMenu() {
		return attributeMenu;
	}

	public String getCategoryId() {
		return categoryId;
	}

	public String getCategoryIdParam() {
		return categoryIdParam;
	}

	public String getCategoryPath() {
		return categoryPath;
	}

	public String getCategoryResult() {
		return categoryResult;
	}

	public CategoryService getCategoryService() {
		return categoryService;
	}

	public String[] getCopyProductCategoryIds() {
		return copyProductCategoryIds;
	}

	public String[] getDelProductCategoryIds() {
		return delProductCategoryIds;
	}

	public String[] getEditProductCategoryIds() {
		return editProductCategoryIds;
	}

	public MenuService getMenuService() {
		return menuService;
	}

	public List getProductAttributeParam() {
		return productAttributeParam;
	}

	public List<Object> getProductCategories() {
		return productCategories;
	}

	public int getProductCategoriesSize() {
		return productCategoriesSize;
	}

	public String[] getProductCategoryIds() {
		return productCategoryIds;
	}

	public ShelfService getShelfService() {
		return shelfService;
	}

	public String[] getShowSeqs() {
		return showSeqs;
	}

	public List<ViewShelfProduct> getViewShelfProducts() {
		return viewShelfProducts;
	}

	public boolean isCheckPrice() {
		return checkPrice;
	}

	public String jsonCategory() throws Exception {
		categoryId = StringUtils.replace(categoryId, " ", "");
		Category category = categoryService.getAvailableCategory(Long.parseLong(categoryId));
		if (null != category) {
			if (StringUtils.equalsIgnoreCase("N", category.getIsEndnode())) {
				categoryResult = "isEndnode";
			} else {
				categoryResult = categoryService.makeCategorieURL(category.getId(), false);
			}
		} else {
			categoryResult = "failure";
		}
		return "jsonCategory";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.Preparable#prepare()
	 */

	public void prepare() throws Exception {
		delProductCategoryIds = null;
		editProductCategoryIds = null;
		copyProductCategoryIds = null;
		clearErrorsAndMessages();
		// 銷售狀態
		attributeMenu = menuService.get("Product.Attribute");
	}

	/**
	 * 分类管理排序设定
	 * 
	 * @return
	 * @throws Exception
	 */
	public String search() throws Exception {
		if (StringUtils.isNotBlank(categoryIdParam)) {
			categoryIdParam = StringUtils.replace(categoryIdParam, " ", "");
			int pageSize = 100;
			tp = JspUtil.pageableTag("pc", pageSize, 10);
			productCategoriesSize = productService.getProductCategoryCountByCategoryId(Long.parseLong(categoryIdParam),
					productAttributeParam, keyword, isCheckPrice());

			tp.setTotalRecords(productCategoriesSize);
			// productCategories

			int maxPage = 0;

			if (tp.getTotalRecords() > 0) {
				maxPage = tp.getTotalRecords() / pageSize;
				if (tp.getTotalRecords() % pageSize > 0) {
					maxPage++;
				}
			}
			int startRow = 0;
			int endRow = 0;
			if (Integer.valueOf(tp.getCurrentPage()) <= maxPage) {
				startRow = pageSize * Integer.valueOf(tp.getCurrentPage() - 1);
				endRow = pageSize * (Integer.valueOf(tp.getCurrentPage()));
			} else {
				startRow = pageSize * (maxPage - 1);
				endRow = tp.getTotalRecords();
			}
			result = productService.getProductCategoryByCategoryIdPager(Long.parseLong(categoryIdParam),
					productAttributeParam, keyword, startRow, endRow, isCheckPrice());

		}
		return "list";
	}

	private TagProperties tp;

	public TagProperties getTp() {
		return tp;
	}

	public void setTp(TagProperties tp) {
		this.tp = tp;
	}

	private Object[] result;

	public Object[] getResult() {
		return result;
	}

	public void setResult(Object[] result) {
		this.result = result;
	}

	/**
	 * 整批商品复制/修改到其他分类
	 * 
	 * @return
	 * @throws Exception
	 */
	public String searchMove() throws Exception {
		if (StringUtils.isNotBlank(categoryIdParam)) {
			categoryIdParam = StringUtils.replace(categoryIdParam, " ", "");
			Category category = categoryService.getAvailableCategory(Long.parseLong(categoryIdParam));
			if (null != category) {
				productCategories = productService.getProductCategoryByCategoryId(Long.parseLong(categoryIdParam), "");
				productCategoriesSize = productCategories.size();
				if (StringUtils.isNotBlank(categoryId)) {
					Category categorySub = categoryService.getAvailableCategory(Long.parseLong(categoryId));
					if (null != categorySub) {
						categoryPath = categoryService.makeCategorieURL(Long.parseLong(categoryId), false);
					}
				}
			} else {
				addActionMessage(categoryIdParam + errorMsg);
			}
		}

		return "list.move";
	}

	public String saveShowWeight() throws Exception {
		if (showSeqs != null && showSeqs.length > 0) {
			for (int i = 0; i < productCategoryIds.length; i++) {
				if (Integer.valueOf(showSeqs[i]) <= 400) {
					ProductCategory pc = (ProductCategory) baseMgr
							.get(ProductCategory.class, Long.valueOf(productCategoryIds[i]));
					Object[] result = baseMgr.queryByHql("from ProdCatSE where categoryId=? and product.productId=?",
							new Object[] { Long.valueOf(categoryIdParam), pc.getProductId() });
					ProdCatSE ps = null;
					if (null != result && result.length > 0) {
						ps = (ProdCatSE) result[0];
					}
					if (null == ps) {
						ps = new ProdCatSE();
						ps.setCategoryId(Long.valueOf(categoryIdParam));
						ps.setCategoryPath(pc.getCategoryPath());
						Product p = (Product) baseMgr.get(Product.class, pc.getProductId());
						ps.setProduct(p);
					}
					ps.setProdCatId(Long.valueOf(productCategoryIds[i]));// 避免ec_product_catgory的PRODCUT_CATEGORY_ID有被異動而ec_prod_cat_se未同步到
					ps.setSortWeight(Integer.valueOf(showSeqs[i]));
					baseMgr.saveOrUpdate(ps);
				}
			}
		}
		return search();
	}

	public void setAttributeMenu(Menu attributeMenu) {
		this.attributeMenu = attributeMenu;
	}

	public void setCategoryId(String categoryId) {
		this.categoryId = categoryId;
	}

	public void setCategoryIdParam(String categoryIdParam) {
		this.categoryIdParam = categoryIdParam;
	}

	public void setCategoryPath(String categoryPath) {
		this.categoryPath = categoryPath;
	}

	public void setCategoryResult(String categoryResult) {
		this.categoryResult = categoryResult;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public void setCheckPrice(boolean checkPrice) {
		this.checkPrice = checkPrice;
	}

	public void setCopyProductCategoryIds(String[] copyProductCategoryIds) {
		this.copyProductCategoryIds = copyProductCategoryIds;
	}

	public void setDelProductCategoryIds(String[] delProductCategoryIds) {
		this.delProductCategoryIds = delProductCategoryIds;
	}

	public void setEditProductCategoryIds(String[] editProductCategoryIds) {
		this.editProductCategoryIds = editProductCategoryIds;
	}

	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public void setProductAttributeParam(List productAttributeParam) {
		this.productAttributeParam = productAttributeParam;
	}

	public void setProductCategories(List<Object> productCategories) {
		this.productCategories = productCategories;
	}

	public void setProductCategoriesSize(int productCategoriesSize) {
		this.productCategoriesSize = productCategoriesSize;
	}

	public void setProductCategoryIds(String[] productCategoryIds) {
		this.productCategoryIds = productCategoryIds;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public void setShelfService(ShelfService shelfService) {
		this.shelfService = shelfService;
	}

	public void setShowSeqs(String[] showSeqs) {
		this.showSeqs = showSeqs;
	}

	public void setViewShelfProducts(List<ViewShelfProduct> viewShelfProducts) {
		this.viewShelfProducts = viewShelfProducts;
	}
}